$(function(){
	new Slideshow($('#slideshow'));
});

function Slideshow(element) {
	this.slideLife  = 5000;
	this.timeout   = null;
	
	this.container = $('<div class="slideshow-container">');
	element.before(this.container);
	this.container.append(element);
	
	this.itemWidth  = element.width();
	this.itemHeight = element.height();

	this.btnPrev   = $('<a />')
		.prependTo(this.container)
		.attr('class', 'btn prev')
		.attr('href', 'javascript:void(0)')
		.css({
			height:this.itemHeight
		})
		.data('slideshow', this)
		.click(function(){
			var ss = $(this).data('slideshow');
			if (ss.timeout) {
				clearTimeout(ss.timeout);
			}
			ss.prev();
		});
	
	this.btnNext   = $('<a />')
		.prependTo(this.container)
		.attr('class', 'btn next')
		.attr('href', 'javascript:void(0)')
		.css({
			height:this.itemHeight
		})
		.data('slideshow', this)
		.click(function(){
			var ss = $(this).data('slideshow');
			if (ss.timeout) {
				clearTimeout(ss.timeout);
			}
			ss.next();
		});
	
	this.ul        = element.children('ul').eq(0);
	this.slides    = this.ul.children('li');
	
	this.ul
		.css({
			width:  this.itemWidth * this.slides.length,
			height: this.itemHeight
		})
		.data('position', 0);
	
	this.slides.css({
		width:  this.itemWidth,
		height: this.itemHeight
	});
	
	this.setPosition = function(pos) {
		this.ul.data('position', pos);
	}
	this.getPosition = function() {
		var pos = parseInt(this.ul.data('position'));
		return pos>0 ? pos : 0;
	}
	
	this._go = function(amount) {
		var pos = this.getPosition();
		pos += amount;
		
		if (pos >= this.slides.length) {
			pos=0;
		}
		if (pos < 0) {
			pos = this.slides.length - 1;
		}
		
		this.setPosition(pos);
		this.ul.animate({
			marginLeft: -1 * pos * this.itemWidth
		});
	}
	
	this.next = function() {
		this._go(1);
	}
	this.prev = function() {
		this._go(-1);
	}
	
	this.play = function(started) {
		started = !!started;
		if (started) {
			this.next();
		}
		
		var self = this;
		if (this.timeout) {
			clearTimeout(this.timeout);
		}
		
		this.timeout = setTimeout(function(){
			self.play(true);
		}, this.slideLife);
	}
	
	this.play();
}